<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/2/26
 * Time: 17:13
 */

namespace app\adminapi\model;
use \think\Model;
use \think\Db;

class DriverCarUse extends Model
{
    /**
     * 获取绑定车辆
     * @param int $driver_id 司机id
     * @return mixed
     */
    public function getUseCar($driver_id=0){
        $list = $this->alias('a')
            ->join('car b','a.car_id = b.car_id','left')
            ->join('car_type c','b.car_type_id = c.car_type_id','left')
            ->join('driver d','a.driver_id = d.driver_id','left')
            ->where('a.driver_id',$driver_id)
            ->field('b.car_id,b.number,c.car_type_name,a.weight,d.name,a.is_default')
            ->order('a.weight')
            ->select();
        return $list;
    }

    /**
     * 增加绑定车辆
     * @param int $driver_id
     * @param array $car
     * @return array
     */
    public function addCar($driver_id=0,$car=[]){
        if($driver_id==0){
            return [0,'司机id错误'];
        }
        if(empty($car)){
            return [0,'车辆不能为空'];
        }
        $carStr   = implode(',',$car);
        $carType  = Db::name('car')->where('car_id','in',$carStr)->column('car_id,car_type_id');
        if(empty($carType)){
            return [0,'车辆不存在'];
        }
        $oldCar   = $this->where('driver_id',$driver_id)->column('car_id');
        if(empty($oldCar)){//司机没有关联车辆时关联的第一辆车为默认车辆
            Db::name('driver')->where('driver_id',$driver_id)->update(['car_id'=>$car[0]]);
        }
        $data     = [];
        $maxWeight= $this->where('driver_id',$driver_id)->max('weight');
        foreach($car as $v){
            if(in_array($v,$oldCar)){
                continue;
            }
            $temp['car_id']      = $v;
            $temp['driver_id']   = $driver_id;
            $temp['car_type_id'] = $carType[$v] ? $carType[$v] : 0;
            $temp['weight']      = $maxWeight + 1;
            $data[]              = $temp;
            $maxWeight           = $maxWeight + 1;
        }
        if(empty($data)){
            return [0,'车辆重复添加'];
        }
        $this->saveAll($data);
        return [1,'绑定成功'];
    }

    public function delCar($driver_id=0,$car=[]){
        if($driver_id==0){
            return [0,'司机id错误'];
        }
        if(empty($car)){
            return [0,'车辆不能为空'];
        }
        $carStr = implode(',',$car);
        $counts = $this->where('car_id','in',$carStr)->where('is_default',0)->where('driver_id',$driver_id)->delete();
        return $counts ==0 ? [0,'车辆不存在或默认车辆无法删除'] : [1,'ok'];
    }

    public function setDefaultCar(){

    }
}